package view;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileWriter;
import java.io.IOException;
import java.util.StringTokenizer;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;

public class HelpFrame extends JFrame
{
	/**
	 * 
	 */
	private static final long serialVersionUID = -5198547881188242684L;

	public static HelpFrame currentHelpFrame = null;
	
	private		JSplitPane	splitPaneV;
	private		JSplitPane	splitPaneH;
	private		JPanel		panelTopics;
	private		JPanel		panelDesc;
	private		JPanel		panelActions;
	private     JTextArea   txtArea;
	private     JLabel      lableDesc;

	public HelpFrame()
	{
		setTitle( "FW Help" );
		
		JPanel topPanel = new JPanel();
		topPanel.setLayout( new BorderLayout() );
		getContentPane().add( topPanel );

		// Create the panels
		createPanelTopics();
		createPanelDesc();
		createPaneActions();

		// Create a splitter pane
		splitPaneV = new JSplitPane( JSplitPane.VERTICAL_SPLIT );
		topPanel.add( splitPaneV, BorderLayout.CENTER );

		splitPaneH = new JSplitPane( JSplitPane.HORIZONTAL_SPLIT );
		splitPaneH.setLeftComponent( panelTopics);
		splitPaneH.setRightComponent(panelDesc);

		splitPaneV.setLeftComponent( splitPaneH );
		splitPaneV.setRightComponent( panelActions );
		
		pack();
		setLocationRelativeTo(null);
		setVisible(false);
		
		currentHelpFrame = this;
	}

	/**
	 * Returns current frame if exists, ales creates it.
	 * @return help frame
	 */
	public static HelpFrame getInctance()
	{
		if(currentHelpFrame == null)
		{
			currentHelpFrame = new HelpFrame();
		}
		
		return currentHelpFrame;
	}
	
	public void createPanelTopics()
	{
		panelTopics = new JPanel();
		JButton mainWinButton   = new JButton( Globals.MAIN + "				" );
		JButton loginWinButton  = new JButton( Globals.LOGIN + "			" );
		JButton errorWinButton  = new JButton( Globals.ERROR + "			" );
		JButton loggerWinButton  = new JButton( Globals.LOGGER + "			" );
		JButton lregExpWinButton  = new JButton( Globals.REG_EXP );
		JButton ruleExpWinButton  = new JButton( Globals.RULES+ "			" );

		panelTopics.setLayout(new BoxLayout(panelTopics, BoxLayout.Y_AXIS));
		panelTopics.add(mainWinButton);
		panelTopics.add(loginWinButton);
		panelTopics.add(errorWinButton);
		panelTopics.add(loggerWinButton);
		panelTopics.add(lregExpWinButton);
		panelTopics.add(ruleExpWinButton);
		
		mainWinButton.addActionListener(new ActionListener() 
		{
			public void actionPerformed(ActionEvent ae) 
		    {
				ShowDesc(Globals.MAIN);
			}
		}
		);
		
		loginWinButton.addActionListener(new ActionListener() 
		{
			public void actionPerformed(ActionEvent ae) 
		    {
				ShowDesc(Globals.LOGIN);
			}
		}
		);
		

		errorWinButton.addActionListener(new ActionListener() 
		{
			public void actionPerformed(ActionEvent ae) 
		    {
				ShowDesc(Globals.ERROR);
			}
		}
		);
		
		loggerWinButton.addActionListener(new ActionListener() 
		{
			public void actionPerformed(ActionEvent ae) 
		    {
				ShowDesc(Globals.LOGGER);
			}
		}
		);
		
		lregExpWinButton.addActionListener(new ActionListener() 
		{
			public void actionPerformed(ActionEvent ae) 
		    {
				ShowDesc(Globals.REG_EXP);
			}
		}
		);

		ruleExpWinButton.addActionListener(new ActionListener() 
		{
			public void actionPerformed(ActionEvent ae) 
		    {
				ShowDesc(Globals.RULES);
			}
		}
		);
	}
	
	public void createPanelDesc()
	{
		panelDesc = new JPanel();
		txtArea = new JTextArea();
		lableDesc = new JLabel("Please Choose A Help topic");
		
		panelDesc.setLayout( new BorderLayout() );
        panelDesc.setPreferredSize( new Dimension(800, 500) );
        panelDesc.setMinimumSize( new Dimension( 100, 50 ) );
        
		panelDesc.add(lableDesc, BorderLayout.NORTH );
		panelDesc.add( txtArea, BorderLayout.CENTER );
	}
	
	public void createPaneActions()
	{ 
		JButton prevButton = new JButton( "Prev" );
		JButton nextButton = new JButton( "Next" );
		JButton saveButton = new JButton( "Save To File" );

		prevButton.setEnabled(false);
		nextButton.setEnabled(false);
		
		panelActions = new JPanel();
		panelActions.setLayout(new BoxLayout(panelActions, BoxLayout.X_AXIS));
		panelActions.add(prevButton);
		panelActions.add(nextButton);
		panelActions.add(saveButton);
		
		saveButton.addActionListener(new ActionListener() 
		{
			public void actionPerformed(ActionEvent ae) 
		    {
				SaveToFile();
			}
		}
		);		
	}

	public void ShowDesc(String btnName)
	{
		txtArea.setText("\r\n");
		
		if(btnName.equals(Globals.MAIN))
		{
			lableDesc.setText("Main Window description");
			txtArea.append("\r\n  Regular expression - window where new regular expression for some protocol can be added. \r\n");
			if(Settings.userMode.equals(UserMode.standartUser))
			{
				txtArea.append("\r\n  Rules - window where you can see rules for the current FW. \r\n");
			}
			else if(Settings.userMode.equals(UserMode.advancedUser))
			{
				txtArea.append("\r\n  Rules - window where you can see rules for the current FW," +
							" add/delete/edit rule," +
							" load/save some ruleset \r\n");				
			}
			txtArea.append("\r\n  Logger -  window where you can see logger reports and statistics. \r\n");
			txtArea.append("\r\n  Exception List - window where you can see error reports. \r\n");
			txtArea.append("\r\n  Help - window where you can see system general help. \r\n");
			txtArea.append("\r\n  Fw on/off - button that turn on/off the FW. \r\n");
			txtArea.append("\r\n  Advanced tab - advanced user options are enabled. \r\n");
			txtArea.append("\r\n  Standart tab - advanced user options are disabled. \r\n");
		}
		else if(btnName.equals(Globals.LOGIN))
		{
			lableDesc.setText("Login Window description");
			txtArea.append("\r\n  This Login window make a login to the FW System Manager. \r\n");
			txtArea.append("\r\n  If you are not an authorize user or forgot your password\r\n");
			txtArea.append("\r\n  please talk to the administrator to add you to the authorize list. \r\n");
			txtArea.append("\r\n  Enter your user name in the user name field, and your password in the password field. \r\n");
			txtArea.append("\r\n  Press the login button - the FW application will be open\r\n");
		}
		else if(btnName.equals(Globals.ERROR))
		{
			lableDesc.setText("Error Window description");
			txtArea.append("\r\n  This Error window show all the errors occured in the FW aplication. \r\n");
			txtArea.append("\r\n  You can press on the clear button - to clean all the errors from the log. \r\n");
			txtArea.append("\r\n  You can press on the save to file button, for saving all the errors to file. \r\n");
			txtArea.append("\r\n  Pressing on the save to file button enable choosing file for saving to. \r\n");
		}
		else if(btnName.equals(Globals.LOGGER))
		{
			lableDesc.setText("Logger Window description");
			txtArea.append("\r\n  This Logger window displays reports of the FW System Manager. \r\n");
			txtArea.append("\r\n  Button Dynamic Mode - turn on iteractive mode of the reports. \r\n");
			txtArea.append("\r\n  Button Static Mode - turn on static mode of the reports. \r\n");
			txtArea.append("\r\n  Button filter display filter options:" +
					"	1. days number 	- the logger data will be displayed for the defined days number. " +
					"	2. protocol		- the logger data where defined protocol is mentioned will be displayed." +
					"	3. IP			- the logger data where defined IP, port, direction are mentioned will be displayed. \r\n");
			txtArea.append("\r\n  Button reset - returns log options to default - without filtering, for the last day. \r\n");
			txtArea.append("\r\n  Button Logger on/off - turns logger on/off appropriatly. \r\n");			
		}
		else if(btnName.equals(Globals.REG_EXP))
		{
			lableDesc.setText("Regular Expression description");
		}
		else if(btnName.equals(Globals.RULES))
		{
			if(Settings.userMode.equals(UserMode.advancedUser))
			{
				lableDesc.setText("Advanced Rules Window description");
				txtArea.append("\r\n  Two tables in this window displays In and Out rules of the FW. \r\n");				
				txtArea.append("\r\n  Button Load and Edit.. - allows to user to load one of defined rulesets (ruleset indentifier is natural number). \r\n");				
				txtArea.append("\r\n  Button Duplicate... - allows to user to save the current ruleset of the FW in the system (ruleset indentifier is natural number). \r\n");				
				txtArea.append("\r\n  Button Restore - loads the current ruleset of the FW. \r\n");				
				txtArea.append("\r\n  Button Set as current - save the ruleset from tables as current FW ruleset. \r\n");				
				txtArea.append("\r\n  Button Add Rule - allows to add rule to the ruleset in the tables. \r\n");				
				txtArea.append("\r\n  Button Delete Rule - allows to delete selected in the table rule from the ruleset. \r\n");				
				txtArea.append("\r\n  Button Edit Rule - allows to edit selected in the table rule in the ruleset. \r\n");				
				txtArea.append("\r\n  * after the window title shows that the ruleset in the tables isn't the current FW ruleset. \r\n");				

			}
			else if(Settings.userMode.equals(UserMode.standartUser))
			{
				lableDesc.setText("Standart Rules Window description");
				txtArea.append("\r\n  Two tables in this window displays In and Out rules of the FW. \r\n");				
			}
		}
		
		panelDesc.updateUI();
		setVisible(true);
	}
	
	private void SaveToFile() 
	{
		JFileChooser chooser = new JFileChooser();
		try
		{
			if(chooser.showSaveDialog(this) ==JFileChooser.APPROVE_OPTION)
			{
				String strFilePath = chooser.getSelectedFile().getPath();
				FileWriter fileOutput = new FileWriter(strFilePath);

				String allText = txtArea.getText() ;
				StringTokenizer st = new StringTokenizer(allText,"\n") ;
				
				fileOutput.write(lableDesc.getText() + "\r\n");
				fileOutput.write("-----------------------------------------\r\n");
				
				while (st.hasMoreTokens()) 
					fileOutput.write(st.nextToken() + "\r\n");
				
				fileOutput.close();
			}
		}
		catch (IOException ex)
		{
			JOptionPane.showMessageDialog(this, "The action can not be done\n" +
						ex.getMessage());
		}
	}
}
